
import { _decorator, Component, Node, EventTouch, PhysicsSystem, geometry, CameraComponent } from 'cc';
import { Constants } from '../data/Constants';
import { CustomEventListener } from '../data/CustomEventListener';
import { BattleManager } from '../managers/BattleManager';
import { UIManager } from '../ui/UIManager';
const { ccclass, property } = _decorator;

/**
 * 游戏控制类, 包括鼠标点击屏幕的判定
 */
@ccclass('GameCtrl')
export class GameCtrl extends Component {
    @property({
        type: CameraComponent,
        displayOrder: 1
    })
    cameraComp: CameraComponent = null!;

    @property({
        type: Node,
        displayOrder: 2,
    })
    //从摄像机的近平面触发, 射出一根射线,射线射到的一个平面
    cameraPanel: Node = null!;

    //定义射线对象,用于向屏幕内的3D世界发射射线
    private _ray: geometry.ray = new geometry.ray();
    start() {
        //注册鼠标点击事件
        this.node.on(Node.EventType.TOUCH_START, this._touchStart, this)
        //注册游戏开始事件
        CustomEventListener.on(Constants.EventName.GAME_START, this._startGame, this)
        CustomEventListener.on(Constants.EventName.GAME_RESTART, this._restartGame, this)
        CustomEventListener.on(Constants.EventName.NEW_LEVEL, this._newLevel, this)
    }

    //鼠标点击屏幕后响应函数
    private _touchStart(event: EventTouch) {
        this.cameraComp?.screenPointToRay(event.getLocationX(), event.getLocationY(), this._ray)

        //基于物理碰撞器的射线监测,raycast是发射函数, 为真发生碰撞
        if (PhysicsSystem.instance.raycast(this._ray)) {
            //射线碰撞结果
            const r = PhysicsSystem.instance.raycastResults;
            for (let i = 0; i < r.length; i++) {
                const item = r[i];
                if (item.collider.node.uuid == this.cameraPanel?.uuid) {
                    console.warn('点到了:' + this.cameraPanel.name + 'hitPoint:' + item.hitPoint)
                    BattleManager.instance().fire(item.hitPoint)
                    return;
                }
            }
        }
    }

    //进入战斗,主界面点击开始游戏的响应函数
    private _startGame() {
        //第三人称切换到第一人称动画
        BattleManager.instance().camAnimationComp.play('camMove')
        BattleManager.instance().startGame()

    }

    //回到主界面,显示的仍然是之前关卡的内容(从失败界面回来)
    private _restartGame() {
        //回收所有的怪物.
        BattleManager.instance().recycleMonsters()
        //第一人称切换到第三人称动画
        BattleManager.instance().camAnimationComp.play('camDefault')
        BattleManager.instance().init()
    }

    //回到主界面, 但是显示的是新的关卡的内容(从胜利界面回来主界面)
    private _newLevel() {
        BattleManager.instance().camAnimationComp.play('camDefault')
        BattleManager.instance().init()
    }
}
